//
//  GoodCataViewController.m
//  SafeFoodManagerDemo
//
//  Created by bob on 2017/10/26.
//  Copyright © 2017年 bob. All rights reserved.
//

#import "GoodCataViewController.h"
#import "GoodCataModel.h"
#import "GoodListTableViewCell.h"
#import "GetRegisterInforModel.h"
#import "ShopRegisterViewController.h"
#import "BatchimportViewController.h"
@interface GoodCataViewController ()<UIActionSheetDelegate>

@property(nonatomic,copy)NSString*SearchKeyWord;

@end

@implementation GoodCataViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    if ([[self getShopID] isEqualToString:@"0"]) {
        self.isEdit = false;
        self.isdeleMore = false;
        
    }
    
    
    
    
    
    
    self.homeTableView.estimatedRowHeight=70;
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"GoodListTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    [self.homeTableView.mj_header beginRefreshing];
    
    //导入成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Assignmentnote) name:@"SaveSuccessnote" object:nil];
}

- (void)Assignmentnote
{
    [self.homeTableView.mj_header beginRefreshing];
}

#pragma mark-tablevie代理方法


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodCataData *data=self.dataArr[indexPath.row];
    
    GoodListTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.isClick=self.isEdit;
    
    cell.deleStatue=self.deleStatue;//是否编辑状态
    
    cell.CataModel=data;
    
    return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        GoodCataData *data=self.dataArr[indexPath.row];
        
        if (self.deleStatue) {
            
            data.Seleclt=!data.Seleclt;
            
            [self ChangeStatues];
            
            [self.homeTableView reloadData];
            
            
        }else{
            //可以点击
            GetRegisterInforModel *model=[GetRegisterInforModel new];
            
            model.token=[LoginStatuesModel getUserToken];
            
            model.catId=[NSString stringWithFormat:@"%ld",data.catId];
            
            model.shopId=[self getShopID];//[NSString stringWithFormat:@"%ld",self.Reqmodel.shopId];
            
            ShopRegisterViewController *Editcata=[ShopRegisterViewController new];
            
            Editcata.requrl=@"/index.php/FoodCheckApi/productTypeAddInfo.json";
            
            Editcata.Reqmodel=model;
            
            Editcata.postUrl=@"/index.php/FoodCheckApi/productTypeAdd.json";
            
            Editcata.title=@"编辑分类";
            
            Editcata.BtnStr=@"保存";
            
            Editcata.OptionSussStr=@"保存成功";
            
            Editcata.block=^()
            {
                
                [self.homeTableView.mj_header beginRefreshing];
            };
            
            
            [self.navigationController pushViewController:Editcata animated:YES];
        }
        
    }
    
    
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.isEdit) {
        
        return YES;
    }
    
    return NO;
    
}


-(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return @"删除";
    
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
    
}


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        
        GoodCataData *data=self.dataArr[indexPath.row];
        
        NSMutableArray *arr=[NSMutableArray array];
        
        [arr addObject:[NSString stringWithFormat:@"%ld",data.catId]];
        
        [self DelPostion:arr];
        
    }
    
}


-(void)DelPostion:(NSArray*)PostID
{
    NSString *params=[HelpWay arrToJSON:PostID];
    
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productTypeDel.json" andrequestTime:5 andParams:@{@"catIds":params} andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        if (responseStatus==1) {
            
            [MBProgressHUD showSuccessMessage:@"删除成功"];
            
            [self.homeTableView.mj_header beginRefreshing];
            
            if (self.deleStatue) {
                //如果处于删除状态
                [self GotoEdit:self.btn];
            }
            
        }else if (responseStatus==0)
        {
            
            [MBProgressHUD showErrorMessage:message];
            
        }else if (responseStatus==2)
        {
            [MBProgressHUD showErrorMessage:message];
            
        }else{
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
            
        }
    }];
    
    
}


#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
     BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:ProductCataType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:ProductCataType andIsLookSelf:isSelf];
    
    Choose.SearchPlace=self.searchName;
    
     Choose.KeyWord=self.SearchKeyWord;
    
     Choose.Lshopid=self.Reqmodel.shopId;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        self.SearchKeyWord=keyword;
        
        self.Reqmodel.params=paras;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}
#pragma mark-编辑事件
-(void)GotoEdit:(UIButton*)sender
{
    sender.selected=!sender.selected;
    
    self.deleStatue=sender.selected;
    
    if (!self.deleStatue) {
        
        for (GoodCataData *data in self.dataArr) {
            
            data.Seleclt=NO;
            
        }
        
        [self ChangeStatues];
    }
    
    [self.homeTableView reloadData];
}


-(void)SeletAll
{
    
    for (GoodCataData *data in self.dataArr) {
        
        data.Seleclt=YES;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//全选

-(void)CanseletAll{
    
    for (GoodCataData *data in self.dataArr) {
        
        data.Seleclt=NO;
        
    }
    
    [self ChangeStatues];
    [self.homeTableView reloadData];
    
}//取消全选

-(void)DelectAll
{
    NSMutableArray *arr=[NSMutableArray array];
    
    for (GoodCataData *data in self.dataArr) {
        
        if (data.Seleclt) {
            
            [arr addObject:[NSString stringWithFormat:@"%ld",data.catId]];
            
        }
        
    }
    
    if (arr.count==0) {
        
        [MBProgressHUD showWarnMessage:@"请至少选择一项"];
        
        return;
    }
    
    [self DelPostion:arr];
}//全部删除


-(void)ChangeStatues{
    
    NSInteger i=0;
    
    for (GoodCataData *data in self.dataArr) {
        
        if (data.Seleclt) {
            i++;
        }
    }
    
    [self.DeleView SelectNum:i];
}

#pragma mark-新增事件
-(void)addNewgoods
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"新增分类",@"批量导入", nil];
    [sheet showInView:self.view];
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { //新增商品
        
    
        //可以点击
        GetRegisterInforModel *model=[GetRegisterInforModel new];
        
        model.token=[LoginStatuesModel getUserToken];
        
        model.shopId=[self getShopID];//[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
        
        ShopRegisterViewController *AddCatas=[ShopRegisterViewController new];
        
        AddCatas.requrl=@"/index.php/FoodCheckApi/productTypeAddInfo.json";
        
        AddCatas.Reqmodel=model;
        
        AddCatas.postUrl=@"/index.php/FoodCheckApi/productTypeAdd.json";
        
        AddCatas.title=@"新增分类";
        
        AddCatas.BtnStr=@"新增";
        
        AddCatas.OptionSussStr=@"新增成功";
        
        AddCatas.block=^()
        {
            
            [self.homeTableView.mj_header beginRefreshing];
        };
        
        [self.navigationController pushViewController:AddCatas animated:YES];
      
        
    } else if (buttonIndex == 1) {//批量导入分类
        
        JobListModel *list=[JobListModel new];
        list.pageSize = 100;
        BatchimportViewController *GoodLsit=[BatchimportViewController new];
        
        if ([self getUserType]==1) {
            
            GoodLsit.isEdit=NO;
            
            GoodLsit.isdeleMore=NO;
            
            list.shopId=[LoginStatuesModel shopId];
        }else if ([self getUserType]==2) {
            
            GoodLsit.isEdit=YES;
            
            GoodLsit.isdeleMore=YES;
            list.shopId = [self getShopID].integerValue;
            
            
        }else{
            
            GoodLsit.isEdit=NO;
            GoodLsit.isdeleMore=NO;
            
//            if (self.shopId!=0) {
//                list.shopId=self.shopId;
//                GoodLsit.isEdit=NO;
//                GoodLsit.AddBtnTitle = @"新增商品";
//            }
            
            if ([self getUserType]==3) {
                
                list.marketId=[LoginStatuesModel getStaffId];
            }
            
        }
        
        GoodLsit.Reqmodel=list;
        GoodLsit.shopId = list.shopId;
        GoodLsit.searchName=@"输入分类名称";
        GoodLsit.AddBtnTitle=@"新增分类";
        GoodLsit.is_goodType = YES;
        GoodLsit.title=@"分类列表";
        
        [self.navigationController pushViewController:GoodLsit animated:YES];
    }
}
//#pragma mark-新增事件
//-(void)addNewgoods
//{
//    //新增商品
//
//    //可以点击
//    GetRegisterInforModel *model=[GetRegisterInforModel new]
//
//    model.token=[LoginStatuesModel getUserToken];
//
//    model.shopId=[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
//
//    ShopRegisterViewController *AddCatas=[ShopRegisterViewController new];
//
//    AddCatas.requrl=@"/index.php/FoodCheckApi/productTypeAddInfo.json";
//
//    AddCatas.Reqmodel=model;
//
//    AddCatas.postUrl=@"/index.php/FoodCheckApi/productTypeAdd.json";
//
//    AddCatas.title=@"新增分类";
//
//    AddCatas.BtnStr=@"新增";
//
//    AddCatas.OptionSussStr=@"新增成功";
//
//    AddCatas.block=^()
//    {
//
//        [self.homeTableView.mj_header beginRefreshing];
//    };
//
//    [self.navigationController pushViewController:AddCatas animated:YES];
//
//}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
    self.Reqmodel.currentPage=1;
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
    self.Reqmodel.currentPage++;
    
    [self loadDatas];
}

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productTypeList.json" andrequestTime:5 andParams:self.Reqmodel.mj_keyValues andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        
        GoodCataModel *InforModel=[GoodCataModel mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
            
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"分类"];
            
            if (InforModel.data.count==0&&self.Reqmodel.currentPage==1) {
                
                [self.dataArr removeAllObjects];
                
                [self.homeTableView reloadData];
                
                self.Type=TBNODateType;
                
                if (self.deleStatue) {
                    //如果处于删除状态
                    [self GotoEdit:self.btn];
                }
                
                self.btn.hidden=YES;
                
            }else if (InforModel.data.count==0&&self.Reqmodel.currentPage!=1){
                
                self.btn.hidden=NO;
                [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
                
            } else{
                
                self.btn.hidden=NO;
                
                if (self.Reqmodel.currentPage==1) {
                    
                    [self.dataArr removeAllObjects];
                    
                }
                
                [self.dataArr addObjectsFromArray:InforModel.data];
                
                [self.homeTableView reloadData];
                
            }
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            if (self.Reqmodel.currentPage>1) {
                
                self.Reqmodel.currentPage=self.Reqmodel.currentPage-1;
            }
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


//获取shopID;

-(NSString*)getShopID{
    NSString * shopID;
    if ([self getUserType]==1) {
        shopID =[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    }else{
        shopID  = [NSString stringWithFormat:@"%ld",self.Reqmodel.shopId];
    }
    
    return  shopID;
    
    
}





@end
